<template>
    <div class="news-carousel">
      <div class="carousel-container">
        <el-carousel
          ref="carouselRef"
          :interval="4000"
          type="card"
          height="300px"
          class="carousel"
        >
          <el-carousel-item v-for="(item, index) in announcements" :key="item.id">
            <div
              class="carousel-item"
              :style="{ backgroundImage: `url(${item.img})` }"
            >
              <h3>{{ item.title }}</h3>
            </div>
          </el-carousel-item>
        </el-carousel>
      </div>
  
      <div class="title-section">
        <h3 class="section-title">公告资讯：</h3>
        <div class="title-list">
          <div
            v-for="(item, index) in announcements"
            :key="item.id"
            class="title-item"
            @mouseenter="jumpToSlide(index)"
          >
            <strong>{{ item.title }}</strong>: 
            <span class="content">{{ item.content }} -</span>
          </div>
        </div>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted } from 'vue';
  import { noticeListService } from '@/api/announcement.js';
  
  const announcements = ref([]);
  const carouselRef = ref(null);
  
  const fetchAnnouncements = async () => {
    try {
      const response = await noticeListService();
      announcements.value = response.data.slice(0, 5); // 提取前五个公告
      console.log('公告列表:', announcements.value);
    } catch (error) {
      console.error('获取公告失败:', error);
    }
  };
  
  const jumpToSlide = (index) => {
    if (carouselRef.value) {
      carouselRef.value.activeIndex = index; // 切换轮播器到对应的项
    }
  };
  
  onMounted(() => {
    fetchAnnouncements();
  });
  </script>
  
  <style scoped>
  .news-carousel {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-top: 40px;
  }
  
  .carousel-container {
    width: 70%;
  }
  
  .carousel {
    position: relative;
  }
  
  .carousel-item {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 300px;
    background-color: red;
    background-size: cover;
    background-position: center;
    color: white; 
    text-align: center;
  }
  
  .title-section {
    width: 70%;
    margin-top: 15px;
  }
  
  .section-title {
    font-weight: bold;
    font-size: 24px;
    margin-bottom: 10px;
  }
  
  .title-list {
    display: flex;
    flex-direction: column;
  }
  
  .title-item {
    display: flex;
    align-items: center;
    padding: 10px 0; /* 上下内边距 */
    color: #333;
    cursor: pointer;
    transition: background-color 0.3s;
    border-bottom: 1px solid #ddd; /* 添加底部边框，模拟表格样式 */
  }
  
  .title-item:hover {
    background-color: #f0f0f0; 
  }
  
  .title-item strong {
    font-weight: bold; 
  }
  
  .content {
    margin-left: 5px; 
    overflow: hidden; 
    white-space: nowrap; 
    text-overflow: ellipsis; 
  }
  </style>
  